//
//  String+Extension+QRCode.swift
//  
//
//  Created by Hoa on 2021/4/13.
//

import Foundation
import UIKit

extension String {
    
    /**
     * 生成二维码
     */
    public func QRCodeImage() -> CIImage? {
        
        let filter = CIFilter(name: "CIQRCodeGenerator")

        filter?.setDefaults()
        
        let data = self.data(using: .utf8)
        
        filter?.setValue(data, forKey: "inputMessage")
        
        let ciImage = filter?.outputImage
        
        return ciImage
    }
}

extension CIImage {
    
    /**
     * 重新绘制改变大小
     */
    public func transitionCIImage(size: CGSize) -> UIImage? {
        
        //获取ciimage的bounds
        let extent = self.extent
        //获取缩放比例
        let scale = min(size.width / extent.width, size.height / extent.height) * UIScreen.main.scale
        //创建bitmap(位图)
        let context = CIContext(options: nil)
        guard let bitImage = context.createCGImage(self, from: extent) else { return nil }
        
        let width = extent.width * scale
        let height = extent.height * scale
        //创建灰度空间
        let cs = CGColorSpaceCreateDeviceGray()
        //创建位图上下文
        let bitRef = CGContext.init(data: nil, width:Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: CGImageAlphaInfo.none.rawValue)
        bitRef?.interpolationQuality = .none
        bitRef?.scaleBy(x: scale, y: scale)
        bitRef?.draw(bitImage, in: extent)
        //绘制
        guard let scaleImage = bitRef?.makeImage() else { return nil }
        
        let image = UIImage.init(cgImage: scaleImage)
        
        return image
    }
}

extension UIImage {
    
    /**
     * 合成中间logo
     */
    public func syntheticCenterIcon(headerImage: UIImage, iconSize: CGSize! = nil) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.size, false, 0)
        
        let qrSizeWidth = self.size.width / self.scale
        let qrSizeHeight = self.size.height / self.scale
        
        let aIconSize = iconSize ?? CGSize(width: qrSizeWidth / 3, height: qrSizeHeight / 3)
        
        let aIconX = (qrSizeWidth / 2.0) - (aIconSize.width / 2.0)
        let aIconY = (qrSizeHeight / 2.0) - (aIconSize.height / 2.0)

        let headerFrame = CGRect(origin: CGPoint(x: aIconX, y: aIconY), size: aIconSize)
        
        self.draw(in: CGRect(x: 0, y: 0, width: qrSizeWidth, height: qrSizeHeight))
        headerImage.draw(in: headerFrame)
        
        let syntheticImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return syntheticImage
    }
}
